package com.springboot.web;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.percentiles.PercentilesAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.StatsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: TongRui乀
 * @Date: 2019/3/12 16:20
 * @description：
 */
@RestController
@RequestMapping("agga")
@Slf4j
public class EsAggaApiController {

    @Autowired
    private TransportClient transportClient;


    /**
     *  聚合查询-- 查询指定字段的最大匹配项
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("max/{indexName}/{type}")
    public String max(@PathVariable String indexName, @PathVariable String type){

        MaxAggregationBuilder agga = AggregationBuilders.max("selfMax").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }


    /**
     *  聚合查询-- 查询指定字段的最小匹配项
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("min/{indexName}/{type}")
    public String min(@PathVariable String indexName, @PathVariable String type){

        MinAggregationBuilder agga = AggregationBuilders.min("min").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }

    /**
     *  聚合查询-- 统计求和
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("sum/{indexName}/{type}")
    public String sum(@PathVariable String indexName, @PathVariable String type){

        SumAggregationBuilder agga = AggregationBuilders.sum("sum").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }


    /**
     *  聚合查询-- 统计求和
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("avg/{indexName}/{type}")
    public String avg(@PathVariable String indexName, @PathVariable String type){

        AvgAggregationBuilder agga = AggregationBuilders.avg("avg").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }


    /**
     *  聚合查询-- 基本统计
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("stats/{indexName}/{type}")
    public String stats(@PathVariable String indexName, @PathVariable String type){

        StatsAggregationBuilder agga = AggregationBuilders.stats("stats").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }


    /**
     *  聚合查询-- 高级统计
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("extendedStats/{indexName}/{type}")
    public String extendedStats(@PathVariable String indexName, @PathVariable String type){

        ExtendedStatsAggregationBuilder agga = AggregationBuilders.extendedStats("extendedStats").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }


    /**
     *  聚合查询-- 基数统计
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("cardinality/{indexName}/{type}")
    public String cardinality(@PathVariable String indexName, @PathVariable String type){

        CardinalityAggregationBuilder agga = AggregationBuilders.cardinality("cardinality").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }


    /**
     *  聚合查询-- 百分比统计
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("percentiles/{indexName}/{type}")
    public String percentiles(@PathVariable String indexName, @PathVariable String type){

        PercentilesAggregationBuilder agga = AggregationBuilders.percentiles("percentiles").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }


    /**
     *  聚合查询-- 个数统计
     * @param indexName
     * @param type
     * @return
     */
    @GetMapping("count/{indexName}/{type}")
    public String count(@PathVariable String indexName, @PathVariable String type){

        ValueCountAggregationBuilder agga = AggregationBuilders.count("count").field("score");

        SearchResponse response = this.transportClient.prepareSearch(indexName).setTypes(type).addAggregation(agga).get();

        List<Aggregation> aggregations = response.getAggregations().asList();

        String json = JSONObject.toJSON(aggregations).toString();

        return json;
    }

}
